import 'package:flutter/material.dart';
import 'package:hotpot/extensions/data.dart';
import 'package:hotpot/models/create_order_req.dart';
import 'package:hotpot/models/shop_detail.dart';
import 'package:hotpot/pages/table/table_page.dart';
import 'package:hotpot/utils/product_utils.dart';
import 'package:hotpot/widgets/styles/icon_box.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:hotpot/widgets/z_container.dart';
import 'package:hotpot/widgets/z_image.dart';

class ShopcarWidget extends StatefulWidget {
  final CreateOrderReq orderData;
  final void Function(int count) onClose;
  final void Function() onSubmit;
  final String name;
  final String? tableColor;

  const ShopcarWidget(this.name, this.tableColor, this.orderData, this.onClose, this.onSubmit, {super.key});

  @override
  State<ShopcarWidget> createState() => _ShopcarWidgetState();
}

class _ShopcarWidgetState extends State<ShopcarWidget> {
  double get totalPrice =>
      widget.orderData.lines
          ?.where((e) => e.comboParentId == null)
          .map((e) => e.priceSubtotal ?? 0)
          .fold<double>(0, (p, e) => p + e) ??
      0;

  int get count =>
      widget.orderData.lines
          ?.where((e) => e.comboParentId == null && e.hasSend == 0)
          .map((e) => e.qty ?? 0)
          .fold<int>(0, (p, e) => p + e) ??
      0;

  List<ShopDetailAttributes> attrList = [];

  bool get hasProduct => (widget.orderData.lines?.indexWhere((e) => e.hasSend == 0) ?? -1) != -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    attrList = detail.attributes!.values.map((e) => ShopDetailAttributes.fromJson(e)).toList();
  }

  @override
  Widget build(BuildContext context) {
    return ZContainer(
      color: const Color(0xFFFFFFFF),
      child: Column(
        children: [
          9.hSizedBox,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // Row(
              //   children: [
              //     25.wSizedBox,
              //     'T${widget.name}'.text(size: 9, bold: true, color: widget.tableColor.color),
              //     10.wSizedBox,
              //     'Orders #${widget.orderData.trackingNumber}'.text(size: 9, bold: true, color: Colors.white),
              //   ],
              // ).sizedBox(width: 150),
              // UserUtils.companyName.text(color: Colors.white, size: 12, bold: true, textAlign: TextAlign.center).expanded(),
              Row(
                children: [
                  'images/img_back.png'
                      .assetImage(width: 10, height: 15)
                      .paddingOnly(left: 15, top: 0)
                      .gestureDetector(onTap: () => widget.onClose(count)),
                ],
              ).expanded(),
              'Tu Pedido'.text(size: 12, color: Colors.black, bold: true, textAlign: TextAlign.center).expanded(),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ZContainer(
                    width: 82,
                    height: 19,
                    radius: 18,
                    margin: const EdgeInsets.only(right: 10),
                    alignment: Alignment.center,
                    color: const Color(0xFF22CE67),
                    child: 'Total: ${totalPrice.fixed}'.text(size: 10, bold: true, color: Colors.white),
                  ),
                ],
              ).expanded(),
            ],
          ),
          if (widget.orderData.lines?.isEmpty ?? true) ...[
            135.hSizedBox,
            'images/img_empty.png'.assetImage(width: 80),
            5.hSizedBox,
            'No se han agregado platos'.text(size: 7, color: Colors.black),
          ],
          if (widget.orderData.lines?.isNotEmpty ?? false) ...[
            16.hSizedBox,
            ListView(
              padding: EdgeInsets.zero,
              children: [
                ...(widget.orderData.lines ??= []).map(lineBox),
              ],
            ).expanded(),
            8.hSizedBox,
            // Column(
            //   mainAxisAlignment: MainAxisAlignment.start,
            //   crossAxisAlignment: CrossAxisAlignment.start,
            //   children: [
            //     'Total:'.text(size: 8, bold: true, color: const Color(0xFF9E9E9E)),
            //     totalPrice.fixed.text(size: 15, bold: true, color: Colors.white),
            //   ],
            // ).paddingSymmetric(horizontal: 20).alignRight(),
            // 5.hSizedBox,
            if (hasProduct)
              ZContainer(
                color: const Color(0xFF22CE67),
                radius: 50,
                height: 23,
                width: 82,
                alignment: Alignment.center,
                margin: const EdgeInsets.only(right: 10, bottom: 15),
                child: 'Envia Pedido'.text(size: 7, bold: true, color: const Color(0xFFFFFFFF)),
              ).gestureDetector(onTap: widget.onSubmit).alignRight(),
          ],
        ],
      ),
    );
  }

  Widget lineBox(CreateOrderReqLines line) {
    var product = detail.productProducts!.firstWhere((e) => e.id == line.productId);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            22.wSizedBox,
            ZImage.memory(bytes: product.image.bytes, width: 20, height: 20),
            9.wSizedBox,
            // product.name.text(size: 7, bold: true, color: Colors.white).sizedBox(width: 66),
            ZContainer(
              width: 66,
              child: Row(
                children: [
                  2.wSizedBox,
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      product.name.text(size: 7, bold: true, color: Colors.black),
                      product.lstPrice.fixed.text(size: 6, color: const Color(0xFFABABAB)),
                    ],
                  ).expanded(),
                ],
              ),
            ),
            26.wSizedBox,
            attrLine(line, product).expanded(),
            // if ((line.hasSend ?? 0) != 0)
            //   line.qty.text(size: 7, color: Colors.white, bold: true, textAlign: TextAlign.center).sizedBox(width: 42),

            if ((line.hasSend ?? 0) == 0)
              ZContainer(
                radius: 50,
                width: 42,
                height: 16,
                color: const Color(0xFFFFBC42),
                child: Row(
                  children: [
                    5.wSizedBox,
                    if (line.qty! == 1)
                      const IconBox(Icons.delete_outlined, 8, 5).gestureDetector(onTap: () {
                        var data = product;
                        var orderData = widget.orderData;
                        if (data.comboIds?.isNotEmpty ?? false) {
                          print('comboIds');
                        } else if (data.attributeLineIds?.isNotEmpty ?? false) {
                          ProductUtils.deleteProduct(orderData.lines ??= [], products: data);
                        } else {
                          ProductUtils.deleteProduct(orderData.lines ??= [], products: data);
                        }
                        setState(() {});
                      }),
                    if (line.qty! > 1)
                      const IconBox(Icons.remove, 8, 6).gestureDetector(onTap: () {
                        if (line.qty! == 1) return;
                        line.qty = line.qty! - 1;
                        line.priceSubtotal = line.qty! * line.priceUnit!;
                        setState(() {});
                      }),
                    line.qty.text(size: 7, color: Colors.white, bold: true, textAlign: TextAlign.center).expanded(),
                    const IconBox(Icons.add, 8, 6).gestureDetector(onTap: () {
                      line.qty = line.qty! + 1;
                      line.priceSubtotal = line.qty! * line.priceUnit!;
                      setState(() {});
                    }),
                    5.wSizedBox,
                  ],
                ),
              ),
            20.wSizedBox,
            line.priceSubtotal.fixed
                .text(size: 8, bold: true, color: Colors.black, textAlign: TextAlign.start)
                .sizedBox(width: 40),
          ],
        ),
      ],
    ).paddingSymmetric(vertical: 5);
  }

  Widget attrLine(CreateOrderReqLines line, ShopDetailProductProducts product) {
    List<String> attrName = [];
    for (var item in line.attributeValueIds ?? <int>[]) {
      for (var attr in attrList) {
        for (var v in attr.values ??= []) {
          if (v.id == item) {
            attrName.add(v.name ?? '');
          }
        }
      }
    }
    return attrName.join('、').text(size: 6, color: const Color(0xFFABABAB), maxLines: 2);
  }
}
